import React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import {
  StatusBar,
  useColorScheme,
  Platform,
  LogBox,
  InteractionManager,
} from 'react-native';
import { SafeAreaProvider } from 'react-native-safe-area-context';
import Icon from 'react-native-vector-icons/Ionicons';
import CustomTabBar from './src/components/CustomTabBar';
import { COLORS } from './src/styles/constants';
import DeviceInfo from 'react-native-device-info';
import { UserProvider } from './src/context/UserContext';
import { AudioPlayerProvider } from './src/context/AudioPlayerContext';
import { ToastContainer } from './src/components/Toast';
import GlobalAudioPlayer from './src/components/GlobalAudioPlayer';
import PermissionsModal from './src/components/PermissionsModal';
import {
  checkAllPermissions,
  requestAllPermissions,
} from './src/utils/permissionsUtils';
import trackPlayerService from './src/services/trackPlayerService';
import baiduTtsService from './src/services/baiduTtsService';
import { checkHermesEnabled } from './check-hermes';

// 忽略特定的警告（补充 index.js 中的设置）
LogBox.ignoreLogs([
  'View #',
  'has a shadow set but cannot calculate shadow efficiently',
]);

// 导入主要屏幕（首页和个人中心需要立即加载）
import HomeScreen from './src/screens/HomeScreen';
import ProfileScreen from './src/screens/ProfileScreen';

// 延迟加载次要屏幕以加快启动速度
const SearchScreen = require('./src/screens/SearchScreen').default;
const MapScreen = require('./src/screens/MapScreen').default;
const AttractionDetailScreen = require('./src/screens/AttractionDetailScreen').default;
const ScenicAreaListScreen = require('./src/screens/ScenicAreaListScreen').default;
const FoodCultureListScreen = require('./src/screens/FoodCultureListScreen').default;
const FoodCultureDetailScreen = require('./src/screens/FoodCultureDetailScreen').default;
const LoginScreen = require('./src/screens/LoginScreen').default;
const EditProfileScreen = require('./src/screens/EditProfileScreen').default;
const SettingsScreen = require('./src/screens/SettingsScreen').default;
const AccountSecurityScreen = require('./src/screens/AccountSecurityScreen').default;
const FeedbackScreen = require('./src/screens/FeedbackScreen').default;
const AboutScreen = require('./src/screens/AboutScreen').default;

const Stack = createStackNavigator();
const Tab = createBottomTabNavigator();

// Tab导航器
function TabNavigator() {
  const [needsCustomTabBar, setNeedsCustomTabBar] = React.useState(false);

  React.useEffect(() => {
    if (Platform.OS !== 'android') {
      setNeedsCustomTabBar(false);
      return;
    }

    const checkDevice = async () => {
      try {
        const brand = await DeviceInfo.getBrand();
        const brandLower = typeof brand === 'string' ? brand.toLowerCase() : '';
        const problematicBrands = ['vivo', 'iqoo'];
        const needsCustom = problematicBrands.some(b => brandLower.includes(b));
        setNeedsCustomTabBar(needsCustom);
      } catch {
        setNeedsCustomTabBar(false);
      }
    };

    checkDevice();
  }, []);

  // 默认TabBar配置
  const defaultScreenOptions = ({ route }: { route: any }) => ({
    tabBarIcon: ({
      focused,
      color,
      size,
    }: {
      focused: boolean;
      color: string;
      size: number;
    }) => {
      let iconName: string = 'ellipse';

      if (route.name === 'Home') {
        iconName = focused ? 'home' : 'home-outline';
      } else if (route.name === 'Profile') {
        iconName = focused ? 'person' : 'person-outline';
      }

      return <Icon name={iconName} size={size} color={color} />;
    },
    tabBarActiveTintColor: COLORS.primary,
    tabBarInactiveTintColor: COLORS.text.quaternary,
    tabBarStyle: {
      backgroundColor: COLORS.background.card,
      borderTopWidth: 1,
      borderTopColor: COLORS.border.light,
      paddingBottom: Platform.OS === 'ios' ? 20 : 8,
      paddingTop: 5,
      height: Platform.OS === 'ios' ? 85 : 60,
    },
    tabBarLabelStyle: {
      fontSize: 12,
      fontWeight: '500' as const,
    },
    headerShown: false,
  });

  if (needsCustomTabBar) {
    // 使用自定义TabBar（只对vivo/iqoo）
    return (
      <Tab.Navigator
        tabBar={props => <CustomTabBar {...props} />}
        screenOptions={{
          headerShown: false,
        }}
      >
        <Tab.Screen
          name="Home"
          component={HomeScreen}
          options={{
            tabBarLabel: '首页',
          }}
        />
        <Tab.Screen
          name="Profile"
          component={ProfileScreen}
          options={{
            tabBarLabel: '我的',
          }}
        />
      </Tab.Navigator>
    );
  } else {
    // 使用默认TabBar（三星等正常设备）
    return (
      <Tab.Navigator screenOptions={defaultScreenOptions}>
        <Tab.Screen
          name="Home"
          component={HomeScreen}
          options={{
            tabBarLabel: '首页',
          }}
        />
        <Tab.Screen
          name="Profile"
          component={ProfileScreen}
          options={{
            tabBarLabel: '我的',
          }}
        />
      </Tab.Navigator>
    );
  }
}

function App() {
  const isDarkMode = useColorScheme() === 'dark';
  const [appReady, setAppReady] = React.useState(false);
  const [showPermissionModal, setShowPermissionModal] = React.useState(false);

  // 初始化应用（优化版：减少延迟，加快启动）
  React.useEffect(() => {
    // 检查 Hermes 是否已启用（仅开发环境）
    if (__DEV__) {
      checkHermesEnabled();
    }
    
    // 立即标记应用为准备好，让UI先渲柑
    setAppReady(true);

    // 使用InteractionManager延迟初始化非关键服务
    // 减少延迟时间，加快启动速度
    const interaction = InteractionManager.runAfterInteractions(() => {
      // 后台异步初始化，不阻塞UI
      // 移除setTimeout，直接执行
      // 初始化 TrackPlayer（后台执行）
      trackPlayerService
        .setupPlayer()
        .catch(error => {
          console.error('❌ TrackPlayer 初始化失败:', error);
        });

      // 预加载百度TTS Token（后台执行）
      baiduTtsService.preloadAccessToken()
        .catch(error => {
          console.warn('⚠️ 预加载百度TTS Token失败:', error);
        });
    });

    return () => {
      interaction.cancel();
    };
  }, []);

  // 检查应用权限（优化版：减少延迟）
  React.useEffect(() => {
    if (appReady) {
      // 减少权限检查延迟，加快响应
      const permissionCheckDelay = Platform.OS === 'ios' ? 300 : 100;
      
      const interaction = InteractionManager.runAfterInteractions(() => {
        const timer = setTimeout(() => {
          checkAppPermissions();
        }, permissionCheckDelay);
        
        return () => clearTimeout(timer);
      });

      return () => {
        interaction.cancel();
      };
    }
  }, [appReady]);

  // 检查权限函数
  const checkAppPermissions = async () => {
    try {
      const permissions = await checkAllPermissions();

      const allGranted =
        permissions.location &&
        permissions.microphone &&
        permissions.speechRecognition;

      if (!allGranted) {
        // 简化逻辑，减少延迟
        requestAnimationFrame(() => {
          setShowPermissionModal(true);
        });
      }
    } catch (error) {
      console.error('❌ 检查权限失败:', error);
    }
  };

  // 处理权限允许
  const handlePermissionAllow = React.useCallback(async () => {
    setShowPermissionModal(false);
    
    try {
      await requestAllPermissions();
    } catch (error) {
      console.error('❌ 请求权限失败:', error);
    }
  }, []);

  // 处理权限拒绝
  const handlePermissionDeny = React.useCallback(() => {
    setShowPermissionModal(false);
  }, []);

  // 如果应用未准备好，显示白屏（避免闪烁）
  if (!appReady) {
    return null;
  }

  return (
    <UserProvider>
      <AudioPlayerProvider>
        <SafeAreaProvider>
          <StatusBar
            barStyle={isDarkMode ? 'light-content' : 'dark-content'}
            translucent
            backgroundColor="transparent"
          />
          <NavigationContainer>
            <Stack.Navigator
              screenOptions={{
                headerShown: true,
                headerTitleAlign: 'center',
                headerBackTitleVisible: false, // 隐藏返回按钮的文字
                headerStyle: {
                  backgroundColor: COLORS.background.primary,
                  shadowColor: 'transparent',
                },
                headerTintColor: COLORS.text.primary,
                headerTitleStyle: {
                  color: COLORS.text.primary,
                  fontWeight: '600',
                },
              }}
            >
              <Stack.Screen
                name="Main"
                component={TabNavigator}
                options={{ headerShown: false }}
              />
              {/* 二级页面统一显示导航栏 */}
              <Stack.Screen
                name="Search"
                component={SearchScreen}
                options={{
                  title: '搜索',
                  headerBackTitle: ' ', // iOS返回按钮不显示文字
                }}
              />
              <Stack.Screen
                name="Map"
                component={MapScreen}
                options={{ headerShown: false }}
              />
              <Stack.Screen
                name="AttractionDetail"
                component={AttractionDetailScreen}
                options={{ headerShown: false }}
              />
              <Stack.Screen
                name="ScenicAreaList"
                component={ScenicAreaListScreen}
                options={{ headerShown: false }}
              />
              <Stack.Screen
                name="FoodCultureList"
                component={FoodCultureListScreen}
                options={{
                  title: '美食·文创',
                  headerBackTitle: ' ', // iOS返回按钮不显示文字
                }}
              />
              <Stack.Screen
                name="FoodCultureDetail"
                component={FoodCultureDetailScreen}
                options={{ headerShown: false }}
              />
              <Stack.Screen
                name="Login"
                component={LoginScreen}
                options={{ headerShown: false }}
              />
              <Stack.Screen
                name="EditProfile"
                component={EditProfileScreen}
                options={{ headerShown: false }}
              />
              <Stack.Screen
                name="Settings"
                component={SettingsScreen}
                options={{ title: '设置' }}
              />
              <Stack.Screen
                name="AccountSecurity"
                component={AccountSecurityScreen}
                options={{ title: '账号与安全' }}
              />
              <Stack.Screen
                name="Feedback"
                component={FeedbackScreen}
                options={{ title: '意见反馈' }}
              />
              <Stack.Screen
                name="About"
                component={AboutScreen}
                options={{ title: '关于我们' }}
              />
            </Stack.Navigator>
            {/* 全局音频播放控制条 */}
            <GlobalAudioPlayer />
          </NavigationContainer>
          {/* 全局Toast容器 */}
          <ToastContainer />
        </SafeAreaProvider>
        {/* 全局权限请求弹窗 - 放在最外层确保不被遮挡 */}
        {React.createElement(PermissionsModal as any, {
          visible: showPermissionModal,
          onAllow: handlePermissionAllow,
          onDeny: handlePermissionDeny,
        })}
      </AudioPlayerProvider>
    </UserProvider>
  );
}

export default App;
